package com.storebits.testsystem.views;

import com.storebits.testsystem.Car;
import com.storebits.testsystem.Carreservation;
import com.storebits.testsystem.Users;
import com.storebits.testsystem.views.util.JsfUtil;
import com.storebits.testsystem.beans.CarreservationFacade;
import com.storebits.testsystem.beans.UsersFacade;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.SelectItem;
import org.primefaces.event.DateSelectEvent;

@ManagedBean(name = "carreservationController")
@SessionScoped
public class CarreservationController implements Serializable {

    private Carreservation current;
    @EJB
    private CarreservationFacade ejbFacade;
    @EJB
    private UsersFacade userFacade;
    private List<Carreservation> items;

    public Carreservation getSelected() {
        if (current == null) {
            current = new Carreservation();
        }
        System.out.println("getSelected()");
        return current;
    }

    private CarreservationFacade getFacade() {
        return ejbFacade;
    }

    public String prepareList() {
        //items = getFacade().findAll();
        return "List";
    }

    public String prepareView(Carreservation item) {
        current = item;
        return "View";
    }

    public String prepareCreate() {
        current = new Carreservation();
        return "Create";
    }

    public String create() {
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            String currUsername = context.getExternalContext().getRemoteUser();
            Users reservationCustomer = userFacade.find(currUsername);
            current.setCustomer(reservationCustomer);
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CarCreated"));
            items = getFacade().findAll();
            return prepareCreate();
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit(Carreservation item) {
        current = item;
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            items = getFacade().findAll();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CarUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy(Carreservation item) {
        current = item;
        performDestroy();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        if (items.size() >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            items = getFacade().findAll();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CarDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public List<Carreservation> getItems() {
        if (items == null) {
            items = ejbFacade.findAll();
        }
        System.out.println("Items:" + items);
        return items;
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }
    
    public void updateTotalSum() {
        Car selectedCar = getSelected().getCar();
        if(selectedCar == null ) { return; }
        BigDecimal carPrice = selectedCar.getPrice();
        
        long numberOfDays = JsfUtil.dateDiff(current.getPickUpDate(), 
                current.getDropOffDate());
        
        double totalSum = carPrice.doubleValue() * numberOfDays;
        double deposit = totalSum * 0.1;
        System.out.println("totalSum: " + totalSum);
        getSelected().setDeposit(new BigDecimal(deposit));
        getSelected().setTotalSum(new BigDecimal(totalSum - deposit));
    }

    public void handleDateSelectDropOfDate(DateSelectEvent event) {  
        FacesContext facesContext = FacesContext.getCurrentInstance();  
        getSelected().setDropOffDate(event.getDate());
        updateTotalSum();
    } 
    
    public void handleDateSelectPickUpDate(DateSelectEvent event) {  
        FacesContext facesContext = FacesContext.getCurrentInstance();  
        getSelected().setPickUpDate(event.getDate());
        updateTotalSum();
    } 
    
    @FacesConverter(forClass = Carreservation.class)
    public static class CarreservationControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CarreservationController controller = (CarreservationController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "carreservationController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Carreservation) {
                Carreservation o = (Carreservation) object;
                return getStringKey(o.getIdCarReservation());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + CarreservationController.class.getName());
            }
        }
    }
}
